<template>
  <a-modal
    :visible="visible"
    :title="modalTitle"
    :width="1200"
    :footer="false"
    @cancel="onCancel"
    @update:visible="onUpdateVisible"
  >
    <!-- <pre>{{ localForm.leaderInstruction }}</pre> -->
    <a-form ref="formRef" :model="localForm" layout="vertical">
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="督办来源">
            <a-input v-model="localForm.source" disabled />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="问题类型">
            <a-input v-model="localForm.problemType" disabled />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="督察要求">
            <a-input v-model="localForm.requirements" disabled />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="领导批示">
            <a-checkbox v-model="localForm.leaderInstruction" style="margin-right: 24px; white-space: nowrap" disabled>
              批示
            </a-checkbox>
            <template v-if="localForm.leaderInstruction">
              <a-input v-model="localForm.leaderRemark" disabled style="width: 180px; margin-left: 12px" />
              <label style="margin-right: 8px; min-width: 70px">相关文件</label>
              <a-upload :file-list="localForm.leaderFiles" disabled />
            </template>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="24">
          <a-form-item label="整改问题清单">
            <a-table
              :columns="problemColumns"
              :data="localForm.problemList ?? []"
              :pagination="false"
              row-key="index"
              bordered
              table-layout="auto"
              style="width: 100%"
            >
              <template #problemDesc="{ record }">
                <a-textarea
                  v-model="record.problemDesc"
                  disabled
                  :auto-size="{ minRows: 2, maxRows: 6 }"
                  style="white-space: pre-wrap; word-break: break-all"
                />
              </template>
            </a-table>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="整改单位">
            <a-input v-model="rfGroupNames" disabled />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="整改人员">
            <a-input v-model="rfUserNames" disabled />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="整改期限">
            <a-input v-model="rfDateDisplay" disabled />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="审核人">
            <a-input v-model="localForm.auditorName" disabled />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="备注">
            <a-input v-model="localForm.remark" disabled />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="相关附件">
            <a-upload :file-list="localForm.attachments" disabled />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="填报单位">
            <a-input v-model="localForm.reportDeptName" disabled />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="填报人">
            <a-input v-model="localForm.reportUser" disabled />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row v-if="!isReceiveMode" :gutter="16">
        <a-col :span="24">
          <a-form-item label="审批意见">
            <a-textarea
              v-model="opinion"
              placeholder="请输入审批意见（可选）"
              :auto-size="{ minRows: 2, maxRows: 4 }"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <div style="text-align: right; margin-top: 24px">
      <a-button @click="onCancel" style="margin-right: 8px">取消</a-button>
      <a-button v-if="!isReceiveMode" @click="onReject" type="outline" style="margin-right: 8px">拒绝</a-button>
      <a-button @click="onConfirm" type="primary">{{ confirmButtonText }}</a-button>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
  import { computed, ref, watch } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import { reviewTask, receiveTask } from '@/api/task';
  import { getUserNameByIds } from '@/api/user';
  import { getGroupNameByIds } from '@/api/group';

  const props = defineProps({
    visible: Boolean,
    form: Object,
    mode: {
      type: String,
      default: 'review', // 'review' 或 'receive'
      validator: (value: string) => ['review', 'receive'].includes(value)
    }
  });
  const emits = defineEmits(['update:visible', 'update:opinion', 'submit', 'refresh', 'approve', 'reject', 'receive']);
  const localForm = ref<any>({});
  const formRef = ref();
  const rfUserNames = ref<string>('');
  const rfGroupNames = ref<string>('');
  const opinion = ref('');

  // 计算属性
  const isReceiveMode = computed(() => props.mode === 'receive');
  const modalTitle = computed(() => (isReceiveMode.value ? '任务接收' : '任务审批'));
  const confirmButtonText = computed(() => (isReceiveMode.value ? '接收' : '同意'));

  watch(
    () => props.visible,
    v => {
      if (!v) opinion.value = '';
    }
  );
  watch(
    () => localForm.leaderInstruction,
    val => {
      if (!val) {
        localForm.leaderRemark = '';
        localForm.leaderFiles = [];
      }
    }
  );
  watch(
    () => localForm.value.rfUsers,
    async newVal => {
      if (newVal) {
        const ids = typeof newVal === 'string' ? newVal.split(',') : newVal;
        try {
          const res = await getUserNameByIds(ids);
          // 这里处理接口返回的字符串数组
          if (Array.isArray(res.data)) {
            const groupNames = res.data.map(item => item.name || '').filter(name => name);
            rfUserNames.value = groupNames.join('，');
          } else {
            rfUserNames.value = '';
          }
        } catch (e) {
          rfUserNames.value = '';
        }
      } else {
        rfUserNames.value = '';
      }
    },
    { immediate: true }
  );
  watch(
    () => localForm.value.rfUnits,
    async newVal => {
      if (newVal) {
        const ids = typeof newVal === 'string' ? newVal.split(',') : newVal;
        try {
          const res = await getGroupNameByIds(ids);
          // 处理接口返回的对象数组，提取 groupName 字段
          if (Array.isArray(res.data)) {
            const groupNames = res.data.map(item => item.groupName || '').filter(name => name);
            rfGroupNames.value = groupNames.join('，');
          } else {
            rfGroupNames.value = '';
          }
        } catch (e) {
          rfGroupNames.value = '';
        }
      } else {
        rfGroupNames.value = '';
      }
    },
    { immediate: true }
  );
  watch(
    () => props.form,
    val => {
      if (val && Object.keys(val).length) {
        localForm.value = { ...val };
      } else {
        localForm.value = {};
      }
    },
    { immediate: true, deep: true }
  );

  const onCancel = () => {
    emits('update:visible', false);
  };

  function onUpdateVisible(val) {
    emits('update:visible', val);
  }

  const onConfirm = async () => {
    if (isReceiveMode.value) {
      await onReceive();
    } else {
      await onApprove();
    }
  };

  const onApprove = async () => {
    try {
      await reviewTask({
        task: localForm.value?.taskId,
        review: true,
        msg: opinion.value || ''
      });
      Message.success('审批成功');
      emits('approve', localForm.value);
      emits('update:visible', false);
      emits('refresh');
    } catch (e) {
      Message.error('审批失败');
    }
  };
  const onReceive = async () => {
    try {
      await receiveTask(localForm.value.taskId);
      Message.success('任务已接收');
      emits('approve', localForm.value);
      emits('update:visible', false);
      emits('refresh');
    } catch (e) {
      Message.error('接收失败');
    }
  };
  const onReject = async () => {
    if (!opinion.value || !opinion.value.trim()) {
      Message.warning('请填写审批意见');
      return;
    }
    try {
      await reviewTask({
        task: localForm.value?.taskId,
        review: false,
        msg: opinion.value
      });
      Message.success('已拒绝');
      emits('reject', localForm.value);
      emits('update:visible', false);
      emits('refresh');
    } catch (e) {
      Message.error('操作失败');
    }
  };

  const problemColumns = [
    { title: '序号', dataIndex: 'index', width: 60 },
    { title: '问题描述', dataIndex: 'problemDesc', slotName: 'problemDesc' }
  ];
  const rfDateDisplay = computed(() => {
    if (!localForm.value?.rfStartDate || !localForm.value?.rfEndDate) return '';
    const d1 = new Date(localForm.value.rfStartDate);
    const d2 = new Date(localForm.value.rfEndDate);
    return `${d1.getFullYear()}年${String(d1.getMonth() + 1).padStart(2, '0')}月${String(d1.getDate()).padStart(2, '0')}日 - ${d2.getFullYear()}年${String(d2.getMonth() + 1).padStart(2, '0')}月${String(d2.getDate()).padStart(2, '0')}日`;
  });
</script>
